package logic

import (
	"context"

	u "godco/internal/model/users"
	"godco/internal/svc"
	"godco/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AuthRequestLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAuthRequestLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AuthRequestLogic {
	return &AuthRequestLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AuthRequestLogic) AuthRequest(req *types.AuthRequest) (resp *types.AuthResp, err error) {
	// todo: add your logic here and delete this line

	data_, err := l.svcCtx.UserModel.FindOneByEmail(l.ctx, req.Email)
	if err == u.ErrNotFound {
		data := u.User{Name: req.Name, Email: req.Email, State: "yes", Token: req.Token}
		err = l.svcCtx.UserModel.Insert(l.ctx, &data)
		if err != nil {
			resp = &types.AuthResp{
				Code:    403,
				Message: err.Error(),
			}
			return resp, nil
		}
	} else {
		data_.Name = req.Name
		data_.Token = req.Token
		_, err = l.svcCtx.UserModel.Update(l.ctx, data_)
		if err != nil {
			resp = &types.AuthResp{
				Code:    403,
				Message: err.Error(),
			}
			return resp, nil
		}
	}
	resp = &types.AuthResp{
		Code:    0,
		Message: "success",
	}
	return resp, nil
}
